import type {  Plugin } from "vite";
import fs from 'node:fs'
import * as electronBuilder from 'electron-builder'
import path from "path";

const buildBackground = () => {
  require("esbuild").buildSync({
    entryPoints: ["electron/mainEntry.ts"],
    bundle: true,
    platform: "node",
    outfile: "./dist/mainEntry.js",
    external: ["electron"],
    // target: 'node20'
  });
}

export let buildPlugin = ():Plugin => {
  return {
    name: "build-plugin",
    // 当 Vite 打包完成后的钩子
    closeBundle() {
      buildBackground()
      // 需要指定package.json main
      const json = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
      json.main = 'mainEntry.js'
      fs.writeFileSync('dist/package.json', JSON.stringify(json, null, 4))
      // bug electron builder 会下载垃圾文件
      fs.mkdirSync('dist/node_modules')

      electronBuilder.build({
        config: {
          directories: {
            output: path.resolve(process.cwd(), 'release'),
            app: path.resolve(process.cwd(), 'dist'),
          },
          // 打成压缩包
          asar: true,
          // 暂时
          appId: 'com.example.app',
          productName: '宇宙最强小吴',
          nsis: {
            oneClick: false, // 取消一键安装
            allowToChangeInstallationDirectory: true, //可以换安装盘
          },
          win: {
            icon: 'build/icons/icon.ico',
            target: ["nsis", "zip"]
          }
        }
      })
    },
  };
};

// plugins\devPlugin.ts
export let getReplacer = () => {
  let externalModels = ["os", "fs", "path", "events", "child_process", "crypto", "http", "buffer", "url", "better-sqlite3", "knex"];
  let result = {} as any;
  for (let item of externalModels) {
    result[item] = () => ({
      find: new RegExp(`^${item}$`),
      code: `const ${item} = require('${item}');export { ${item} as default }`,
    });
  }
  result["electron"] = () => {
    let electronModules = ["clipboard", "ipcRenderer", "nativeImage", "shell", "webFrame"].join(",");
    return {
      find: new RegExp(`^electron$`),
      code: `const {${electronModules}} = require('electron');export {${electronModules}}`,
    };
  };
  return result;
};